package com.frank.controller;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author 麦金
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Resource
    DiscoveryClient discoveryClient;

    @Resource
    LoadBalancerClient loadBalancerClient;

    @Resource
    RestTemplate restTemplate;


    @RequestMapping(value = "/see",method = RequestMethod.GET)
    public String see() {
        String services = "Services: " + discoveryClient.getServices();
        System.out.println(services);
        return services;
    }

    @RequestMapping(value = "/consumer",method = RequestMethod.GET)
    public String dc() {
        ServiceInstance serviceInstance = loadBalancerClient.choose("eureka-client");
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/dc";
        System.out.println(url);
        return restTemplate.getForObject(url, String.class);
    }

    /**
     * 取消loadBalancerClient的方式，使用ribbon
     * @return
     */
    @GetMapping("/consumer2")
    public String dc2() {
        return restTemplate.getForObject("http://eureka-client/dc", String.class);
    }

}
